<template>
  <div class="app-container">
    <common-table
      :colnames="colnames"
      :list-data="listData"
      :list-loading="listLoading"
      :is-multiple="isMultiSelect"
      :buttons="buttons"
      :custom-buttons="customButtons"
      :custom-selectors="customSelectors"
      :query="routeQuery"
      @fetchData="fetchData"
      @itemNew="itemNew"
      @itemEdit="itemEdit"
      @itemDelete="itemDelete"
      @onItemClick="onItemClick"
      @onCustomButtonClick="onCustomButtonClick"
    >
      <template v-slot:default>
        <div class="station-info">
          <div class="left">
            <el-row>
              <el-col>
                <svg-icon
                  style="width: 64px; height: 64px"
                  icon-class="dashboard"
                />
              </el-col>
            </el-row>
          </div>
          <div class="right">
            <el-row>
              <el-col class="t1">
                场站：{{ stationName }}

                <span style="float: right">
                  <el-button
                    type="primary"
                    size="mini"
                    style="margin-right: 15px"
                    @click="manageSection"
                  >
                    管理分区
                  </el-button>
                  <el-switch
                    v-model="stationStatus"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="onStationStatusChange"
                  />
                </span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8" class="t2"
                ><span class="bold">创建时间：</span
                >{{ station.createDate | formatDateHM }}</el-col
              >
              <el-col :span="8" class="t2"
                ><span class="bold">地址：</span>{{ station.addrDesc }}</el-col
              >
              <el-col :span="8" class="t2"
                ><span class="bold">分区数量：</span
                >{{ station.sectionCount || 0 }}</el-col
              >
            </el-row>
            <el-row>
              <el-col :span="8" class="t2"
                ><span class="bold">备注：</span>{{ station.remark }}</el-col
              >
              <el-col :span="8" class="t2"
                ><span class="bold">更新时间：</span
                >{{ station.createDate | formatDateHM }}</el-col
              >
              <el-col :span="8" class="t2"
                ><span class="bold">价格牌数量：</span
                >{{ listData.total }}</el-col
              >
            </el-row>
          </div>
        </div>
      </template>
      <template v-slot:rightPannel>
        <!-- <el-button size="mini" type="default" @click="downloadTemplate()">下载模板</el-button>
          <el-button size="mini" type="primary" style="margin-right:80px;" @click="importData()">批量导入</el-button> -->
        <el-input
          v-model="listQuery.devName"
          placeholder="价牌名称"
          clearable
          class="etag"
          size="mini"
        />
        <!-- <el-input
          v-model="listQuery.templateId"
          placeholder="价格编号"
          clearable
          class="etag"
          size="mini"
        /> -->
        <el-input
          v-model="listQuery.devIMEI"
          placeholder="价牌IMEI"
          clearable
          class="etag"
          size="mini"
        />
        <el-button
          type="primary"
          size="mini"
          class="ml5"
          @click="fetchData(listQuery)"
          >查询</el-button
        >
        <el-button
          type="default"
          size="mini"
          class="ml5"
          @click="exportData(listQuery)"
          >导出</el-button
        >
      </template>
    </common-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <detail-edit
        :values="editValues"
        :edit-type="editType"
        @onCancel="dialogVisible = false"
        @onSubmit="onSubmit"
      />
    </el-dialog>
  </div>
</template>
<style scoped>
.el-row {
  margin-bottom: 10px;
}
.left {
  width: 80px;
  margin: 20px;
}
.right {
  flex: auto;
}
.t1 {
  font-size: 1.5em;
  margin-top: 10px;
  margin-bottom: 10px;
}
.t2 {
  font-size: 1em;
}
.bold {
  font-weight: bold;
}
.station-info {
  display: flex;
  margin-bottom: 20px;
}
.etag {
  width: 150px;
  margin-right: 5px;
}
</style>
<script>
import { mapGetters } from "vuex";
import CommonTable from "../commontable";
// import CommonEdit from '../commontable/edit'
import { getEtagList, delEtag, addEtag, putEtag, exportEtag } from "@/api/etag";
import { addPrice } from "@/api/price";
import { batchDel, mergeQuerrys } from "@/utils";
import { putStation, getStation } from "@/api/station";
import DetailEdit from "./devedit.vue";
export default {
  name: "Detail",
  components: { CommonTable, DetailEdit },
  data() {
    return {
      station: {},
      stationStatus: true,
      customSelectors: [
        // { name: 'opt1', options: [
        //   { name: 'select1', value: '1' },
        //   { name: 'select2', value: '2' }
        // ] }
      ],
      buttons: [{ name: "新建价牌" }, { name: "修改" }, { name: "删除" }],
      customButtons: [
        { name: "读取状态", type: "default", data: {} },
        // { name: '下载模板', type: 'default', data: {}},
        // { name: '批量导入', type: 'primary', data: {}}
      ],
      colnames: [
        {
          displayName: "序号",
          colName: "id",
          dataType: "indexNo",
          colWidth: "64px",
          sortable: false,
        },
        { displayName: "价牌名称", colName: "devName", sortable: false },
        {
          displayName: "所属分区",
          colName: "section.sectionName",
          sortable: false,
        },
        // { displayName: '价牌编号', colName: 'templateId', sortable: false, queryable: true },
        {
          displayName: "显示价格",
          colName: "usingTemplate.fileUrl",
          dataType: "image",
          colWidth: "120px",
          sortable: false,
        },
        {
          displayName: "设定价格",
          colName: "settingTemplate.fileUrl",
          dataType: "image",
          colWidth: "120px",
          sortable: false,
        },
        {
          displayName: "同步状态",
          colName: "syncStatus",
          sortable: false,
          formater: (val, row) => {
            return row.usingTemplate &&
              row.settingTemplate &&
              row.usingTemplate.otaId === row.settingTemplate.otaId
              ? "是"
              : "否";
          },
        },
        {
          displayName: "在线状态 ",
          colName: "devUpdateTime",
          sortable: false,
          formater: (val, row) => {
            const time = row.devUpdateTime;
            const d = new Date(time);
            const now = Date.now();
            const diff = (now - d) / 1000;
            return diff < 24 * 3600 ? "在线" : "离线";
          },
        },
        { displayName: "价牌IMEI编号", colName: "devIMEI", sortable: false },
        { displayName: "SIM卡号", colName: "devCCID", sortable: false },
        { displayName: "价牌类型", colName: "priceTypeDesc", sortable: false },
        { displayName: "信号数值 ", colName: "devRSSI", sortable: false },
        { displayName: "设备电压 ", colName: "devBat", sortable: false },

        {
          displayName: "操作",
          dataType: "oprators",
          data: {
            ops: [
              { name: "编辑", click: "itemUpdate" },
              { name: "删除", click: "itemDelete" },
            ],
          },
        },
        // { displayName: '价牌Id', colName: 'templateId', dataType: 'imglink', link: { name: 'priceDetail' }, colWidth: '120px' },
        // { displayName: '设备ID', colName: 'devId', sortable: false, hidden: true },
        // { displayName: 'RSSI', colName: 'devRSSI', sortable: false },
        // { displayName: '所属场站', colName: 'station.stationName', sortable: false },
        // { displayName: '所属车位', colName: 'place.placeName', sortable: false }
      ],
      editType: "edit",
      editValues: {},
      listData: {},
      listLoading: false,
      isMultiSelect: true,
      dialogVisible: false,
      dialogTitle: "新建",
      stationName: "---",
      listQuery: {},
    };
  },
  computed: {
    ...mapGetters(["user", "name", "avatar", "roles"]),
    routeQuery() {
      return this.$route.params.query;
    },
    routeStationId() {
      return this.$route.params.stationId;
    },
    fromItem() {
      return this.$route.params.fromItem;
    },
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      // 如果从路由传过数据来了，就直接采用
      if (this.$route.params.fromItem) {
        if (this.$route.params.stationName) {
          this.stationName = this.$route.params.stationName;
        }
        if (this.$route.params.fromItem) {
          this.station = Object.assign(
            this.station,
            this.$route.params.fromItem
          );
        }
        this.stationStatus = this.station.stationStatus === 1;
      } else {
        // 没传数据，比如浏览器刷新了，就重新获取当前的场站信息
        getStation(this.routeStationId).then((ret) => {
          console.log("station:", ret);
          this.station = ret.data;
          this.stationName = this.station.stationName;
          this.stationStatus = this.station.stationStatus === 1;
        });
      }
    });
  },
  methods: {
    fetchData(listQuery) {
      this.listQuery = listQuery;
      console.log("fetchData", listQuery);
      this.listLoading = true;
      const keyDefs = [
        { key: "devName", matchType: "like" },
        { key: "templateId", matchType: "like" },
        { key: "devIMEI", matchType: "like" },
      ];

      getEtagList(
        mergeQuerrys(keyDefs, listQuery),
        this.$route.params.stationId
      )
        .then((ret) => {
          console.log("ret", ret);
          console.log(ret.data.records);
          this.listData = ret.data;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    itemNew() {
      console.log("etag New", this.$route.params.stationId);
      this.editType = "add";
      this.dialogTitle = "新建价牌";
      this.editValues = {
        stationId: this.$route.params.stationId,
        sectionId: "",
        templateType: 1,
      };
      this.dialogVisible = true;
    },
    itemEdit({ type, item, items }) {
      // 格式化数据
      let formItem = Object.assign({}, item);
      formItem = Object.assign(formItem, item.settingTemplate);
      formItem.id = item.id;
      console.log("itemEdit", item, formItem);
      this.editType = "edit";
      this.editValues = formItem;
      this.dialogTitle = "修改价牌";
      this.dialogVisible = true;
    },
    itemDelete({ type, item, items }) {
      console.log("itemDelete");
      if (type === "one") {
        delEtag({ etagId: item.id }).then((ret) => {
          this.$message({
            type: "success",
            message: "删除成功！",
          });
          this.fetchData(this.listQuery);
        });
      } else if (type === "multi") {
        batchDel(delEtag, items, { idname: "etagId", idvalue: "id" }).then(
          (ret) => {
            this.$message({
              type: "success",
              message: "删除成功！",
            });
            this.fetchData(this.listQuery);
          }
        );
      }
    },
    onSubmit(formData) {
      console.log("onSubmit", formData);
      if (this.editType === "add") {
        // 新建
        // if (formData.priceType == 10) {
        formData.price1 = formData.unit1
          ? parseFloat(
              (
                parseFloat(formData.unit1) + parseFloat(formData.service1)
              ).toFixed(2)
            )
          : null;
        formData.price2 = formData.unit2
          ? parseFloat(
              (
                parseFloat(formData.unit2) + parseFloat(formData.service2)
              ).toFixed(2)
            )
          : null;
        formData.price3 = formData.unit3
          ? parseFloat(
              (
                parseFloat(formData.unit3) + parseFloat(formData.service3)
              ).toFixed(2)
            )
          : null;
        formData.price4 = formData.unit4
          ? parseFloat(
              (
                parseFloat(formData.unit4) + parseFloat(formData.service4)
              ).toFixed(2)
            )
          : null;
        formData.price5 = formData.unit5
          ? parseFloat(
              (
                parseFloat(formData.unit5) + parseFloat(formData.service5)
              ).toFixed(2)
            )
          : null;
        formData.price6 = formData.unit6
          ? parseFloat(
              (
                parseFloat(formData.unit6) + parseFloat(formData.service6)
              ).toFixed(2)
            )
          : null;
        formData.price7 = formData.unit7
          ? parseFloat(
              (
                parseFloat(formData.unit7) + parseFloat(formData.service7)
              ).toFixed(2)
            )
          : null;
        formData.price8 = formData.unit8
          ? parseFloat(
              (
                parseFloat(formData.unit8) + parseFloat(formData.service8)
              ).toFixed(2)
            )
          : null;
        formData.price9 = formData.unit9
          ? parseFloat(
              (
                parseFloat(formData.unit9) + parseFloat(formData.service9)
              ).toFixed(2)
            )
          : null;
        formData.price10 = formData.unit10
          ? parseFloat(
              (
                parseFloat(formData.unit10) + parseFloat(formData.service10)
              ).toFixed(2)
            )
          : null;
        formData.price11 = formData.unit11
          ? parseFloat(
              (
                parseFloat(formData.unit11) + parseFloat(formData.service11)
              ).toFixed(2)
            )
          : null;
        formData.price12 = formData.unit12
          ? parseFloat(
              (
                parseFloat(formData.unit12) + parseFloat(formData.service12)
              ).toFixed(2)
            )
          : null;
        // }
        addPrice(formData).then((template) => {
          formData.templateId = template.data.id;
          addEtag(formData).then((ret) => {
            console.log("add ret", ret);
            this.$message({
              type: "success",
              message: "添加成功！",
            });
            this.dialogVisible = false;
            this.fetchData(this.listQuery);
          });
        });
      } else {
        console.log(formData);
        // if (formData.priceType == 10) {
        formData.price1 = formData.unit1
          ? parseFloat(
              (
                parseFloat(formData.unit1) + parseFloat(formData.service1)
              ).toFixed(2)
            )
          : null;
        formData.price2 = formData.unit2
          ? parseFloat(
              (
                parseFloat(formData.unit2) + parseFloat(formData.service2)
              ).toFixed(2)
            )
          : null;
        formData.price3 = formData.unit3
          ? parseFloat(
              (
                parseFloat(formData.unit3) + parseFloat(formData.service3)
              ).toFixed(2)
            )
          : null;
        formData.price4 = formData.unit4
          ? parseFloat(
              (
                parseFloat(formData.unit4) + parseFloat(formData.service4)
              ).toFixed(2)
            )
          : null;
        formData.price5 = formData.unit5
          ? parseFloat(
              (
                parseFloat(formData.unit5) + parseFloat(formData.service5)
              ).toFixed(2)
            )
          : null;
        formData.price6 = formData.unit6
          ? parseFloat(
              (
                parseFloat(formData.unit6) + parseFloat(formData.service6)
              ).toFixed(2)
            )
          : null;
        formData.price7 = formData.unit7
          ? parseFloat(
              (
                parseFloat(formData.unit7) + parseFloat(formData.service7)
              ).toFixed(2)
            )
          : null;
        formData.price8 = formData.unit8
          ? parseFloat(
              (
                parseFloat(formData.unit8) + parseFloat(formData.service8)
              ).toFixed(2)
            )
          : null;
        formData.price9 = formData.unit9
          ? parseFloat(
              (
                parseFloat(formData.unit9) + parseFloat(formData.service9)
              ).toFixed(2)
            )
          : null;
        formData.price10 = formData.unit10
          ? parseFloat(
              (
                parseFloat(formData.unit10) + parseFloat(formData.service10)
              ).toFixed(2)
            )
          : null;
        formData.price11 = formData.unit11
          ? parseFloat(
              (
                parseFloat(formData.unit11) + parseFloat(formData.service11)
              ).toFixed(2)
            )
          : null;
        formData.price12 = formData.unit12
          ? parseFloat(
              (
                parseFloat(formData.unit12) + parseFloat(formData.service12)
              ).toFixed(2)
            )
          : null;
        // }
        // 修改
        addPrice(formData).then((template) => {
          formData.templateId = template.data.id;
          putEtag(formData).then((ret) => {
            console.log("edit ret", ret);
            this.$message({
              type: "success",
              message: "修改成功！",
            });
            this.dialogVisible = false;
            this.fetchData(this.listQuery);
          });
        });
      }
    },
    onItemClick({ col, row }) {
      // 点击事件
      if (col.link) {
        if (col.link.name === "priceDetail") {
          // 价格牌详情
          console.log("priceDetail", row);
        }
      }
    },
    onStationStatusChange(val) {
      console.log(996, val);
      putStation({
        id: this.fromItem.id,
        stationStatus: val ? 1 : 0,
      }).then((ret) => {
        console.log(ret);
      });
    },
    onCustomButtonClick({ target, data }) {
      console.log(target.name, "点击了");
      switch (target.name) {
        case "读取状态":
          this.fetchData(this.listQuery);
          break;
        case "下载模板":
          break;
        case "批量导入":
          break;
      }
    },
    exportData(listQuery) {
      listQuery.stationId = this.$route.params.stationId;
      const keyDefs = [
        { key: "devName", matchType: "like" },
        { key: "templateId", matchType: "like" },
        { key: "devIMEI", matchType: "like" },
        { key: "stationId", matchType: "match" },
      ];

      exportEtag(mergeQuerrys(keyDefs, listQuery)).then((ret) => {
        console.log(ret);
      });
    },
    manageSection() {
      this.$router.push({
        name: "Section",
        params: {
          stationId: this.station.id,
          stationName: this.station.stationName,
        },
      });
    },
  },
};
</script>
